import React, { PureComponent } from 'react';
import {
  TextInput as RNTextInput,
  TouchableOpacity,
  Image,
  View,
  StyleSheet,
} from 'react-native';

import { ic_clear } from '../assets';

export default class TextInput extends PureComponent {
  static defaultProps = {
    hideClear: false,
    value: '',
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  focus = () => {
    this.textInput && this.textInput.focus && this.textInput.focus();
  };

  blur = () => {
    this.textInput && this.textInput.blur && this.textInput.blur();
  };

  render() {
    const { style, hideClear, onChangeText, ...inputProps } = this.props;
    return (
      <View style={styles.container}>
        <RNTextInput
          ref={c => (this.textInput = c)}
          style={[styles.input, this.props.style]}
          {...inputProps}
          allowFontScaling={false}
          underlineColorAndroid="transparent"
          onChangeText={this.onChangeText}
          onFocus={this.onFocus}
          onBlur={this.onBlur}
        />
        {this.renderClear()}
      </View>
    );
  }

  renderClear() {
    return !this.props.hideClear && this.props.value && this.state.focus ? (
      <TouchableOpacity onPress={this.onClearPress}>
        <Image style={styles.clear} resizeMode={'contain'} source={ic_clear} />
      </TouchableOpacity>
    ) : null;
  }

  onFocus = () => {
    this.setState({
      focus: true,
    });
  };
  onBlur = () => {
    this.setState({
      focus: false,
    });
  };

  onClearPress = () => {
    if (this.props.onClearPress) {
      this.props.onClearPress(this.props.type);
    } else {
      this.props.onChangeText && this.props.onChangeText('');
    }
  };

  onChangeText = text => {
    this.props.onChangeText && this.props.onChangeText(text);
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  input: {
    flex: 1,
    padding: 0,
  },
  clear: {
    width: 16,
    height: 16,
  },
});
